package com.tchhy.mvplibrary.ui.fragment

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.ComponentName
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.core.app.ActivityCompat
import com.tbruyelle.rxpermissions2.RxPermissions
import com.trello.rxlifecycle2.components.support.RxFragment
import com.umeng.commonsdk.statistics.common.DeviceConfig.getPackageName


/**
 *
 * Author: wfy
 *
 * time: 2018/11/22
 *
 */
open class PermissionFragment : RxFragment() {
    private var mRxPermissions: RxPermissions? = null
     val CODE_REQUEST_PERMISSIONS: Int = 3000

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mRxPermissions = RxPermissions(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        mRxPermissions = null
    }

    @SuppressLint("CheckResult")
    fun requestPermission(vararg requests: String, success: () -> Unit) {
        mRxPermissions
                ?.requestEachCombined(*requests)
                ?.subscribe { permission ->
                    if (permission.granted) {
                        success.invoke()
                    } else if (!permission.shouldShowRequestPermissionRationale) {
                        var str = ""
                        when(permission.name){
                            "android.permission.CAMERA"->{
                                str = "相机"
                            }
                            "android.permission.RECORD_AUDIO"->{
                                str = "录音"
                            }
                            "android.permission.ACCESS_FINE_LOCATION"->{
                                str = "定位"
                            }
                            "android.permission.WRITE_EXTERNAL_STORAGE"->{
                                str = "写入存储"
                            }

                        }
                        showDialog(str)
                    }
                }
    }

    private fun showDialog(name:String) {
        AlertDialog.Builder(activity).setTitle("提示")
                .setMessage("您拒绝了${name}权限，可能会造成部分功能无法正常使用，是否现在去授予权限？")
                .setPositiveButton("去授权") { dialog, _ ->
                    dialog.dismiss()
                    goGrantedPermission()
                }
                .setNegativeButton("取消", null)
                .show()
    }

    /*
       引导用户至设置页手动授权
   */
    @SuppressLint("ObsoleteSdkInt")
    private fun goGrantedPermission() {
/*
        val appIntent = context!!.packageManager.getLaunchIntentForPackage("com.iqoo.secure")
        if (appIntent != null) {
            startActivity(appIntent)
            floatingView = SettingFloatingView(this, "SETTING", getApplication(), 0)
            floatingView.createFloatingView()
            return
        }*/
        /*val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        if (Build.VERSION.SDK_INT >= 9) {
            intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS";
            intent.data = Uri.fromParts("package", activity!!.packageName, null)
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.action = Intent.ACTION_VIEW
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", activity!!.packageName)
        }
        startActivity(intent)*/

        try {
            val intent = Intent()
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            val comp =
                ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity")//华为权限管理
            intent.component = comp
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            startActivity(getAppDetailSettingIntent())
        }


    }

    fun getAppDetailSettingIntent(): Intent{
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        if (Build.VERSION.SDK_INT >= 9) {
            intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS";
            intent.data = Uri.fromParts("package", activity!!.packageName, null)
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.action = Intent.ACTION_VIEW
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", activity!!.packageName)
        }
        return intent
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode){
            CODE_REQUEST_PERMISSIONS -> {//


            }
        }
    }

}